import store from '../store'
import { baseURL } from './url.js'

const defaultOptions = {
	data: {},
	method: 'POST',
	dataType: 'json',
	ContentType: 'application/json;charset=UTF-8',
	...baseURL
};

//普通请求
export function request(url, options = {}, header = {}) {
	if (!url) {
		return Promise.reject({});
	} else {
		url = url.replace(/^\/+/, '');
	}

	url += (url.indexOf('?') !== -1 ? '&' : '?') + '_=' + Date.now();

	options = Object.assign({}, defaultOptions, options);

	const Authorization = store.state.Authorization || uni.getStorageSync('Authorization');

	const {
		ctx,
		data,
		method,
		dataType,
		ContentType
	} = options;
	if (!/^(http)[s]*:/.test(url)) {
		url = [ctx, '/', url].join('');
	}
	return new Promise((resolve, reject) => {
		const requestTask = uni.request({
			url,
			data,
			method: method.toUpperCase(),
			dataType,
			header: Object.assign({
				Authorization,
				'Content-Type': ContentType
			}, header),
			success: res => {
				// uni.hideLoading();
				if (res.statusCode === 404 || res.statusCode === 403) {

				} else if (res.statusCode === 500) {
					reject({
						msg: '系统异常，请稍后重试！'
					});
				} else {
					const data = res.data || {};
					if (Number(data.code) === 8803) {
						data.data = {};
						resolve(data);
					} else if (Number(data.code) === 0 || Number(data.code) === 200 || data
						.success) {
						resolve(data);
					} else {
						const msg = data.msg || '';
						if (msg === '发生空指针异常' || msg === '') {
							console.error('请求参数：', url, options, '请求响应结果：', data);
							data.msg = '请求失败，稍候重试！';
						} else {
							uni.showToast({
								title: msg.replace('对不起，', ''),
								icon: 'none',
							})
						}
						reject(data);
					}
				}
			},
			error: res => {
				uni.hideLoading();
				reject(res);
			}
		});
	}).catch(res => {
		throw res;
	});
};

export const freeRequest = request;
export const loginRequest = request;

//请求队列
const Queue = [];

//需要登录的接口请求时，进入挂起队列
export function needLoginRequest(url, options = {}, header = {}) {
	return new Promise((resolve, reject) => {
		Queue.push({
			params: [url, options, header],
			callback: (params) => {
				console.log(url, '执行挂起请求')
				resolve(request(...params).catch(e => { throw e; }));
			}
		});
		console.log(url, '请求进入挂起队列')
	}).catch(res => {
		throw res;
	});
}

//执行挂起队列
export function executeQueue() {
	while (Queue.length) {
		const req = Queue.shift();
		req.callback(req.params);
	}
}

//上传文件
export function uploadFile(url, options = {}) {
	if (!url) {
		return Promise.reject({});
	} else {
		url = url.replace(/^\/+/, '');
	}
	if (!/^(http)[s]*:/.test(url)) {
		url = [defaultOptions.ctx, '/', url].join('');
	}
	options = Object.assign({
		header: {
			Authorization,
			'Content-Type': 'multipart/form-data'
		}
	}, options);

	const {
		fileList = [],
			fileType,
			header,
			formData = {}
	} = options, promiseWorkList = [];

	const Authorization = uni.getStorageSync('Authorization');

	if (fileList.length) {
		for (let file of fileList) {
			promiseWorkList.push(
				new Promise((resolve, reject) => {
					uni.uploadFile({
						url,
						header: {
							Authorization
						},
						fileType,
						formData,
						filePath: file.uri,
						name: file.name,
						success: function(res) {
							if (res.statusCode === 200) {
								resolve(res.data);
							} else {
								reject({});
							}
							uni.hideLoading();
						},
						fail: function(res) {
							reject({});
							uni.hideLoading();
						}
					});
				})
			);
		}
		return Promise.all(promiseWorkList);
	} else {
		const data = formData
		return request(url, {
			data
		}).catch(res => {
			throw res;
		});;
	}
}


//上传图片
export function uploadMultiImage(url, options = {}) {
	Object.assign(options, {
		fileType: 'image'
	});
	return uploadFile(url, options);
}
